<?php

/***** User functions *****/

// 得到当前用户的ID号
function get_currentuserid($echo=true){
	global $user_ID;
	$user_ID=0;
	
	get_currentuserinfo();
	if($echo)
		echo $user_ID;
	else
		return $user_ID;
}

if ( !function_exists('get_currentuserinfo') ) :
function get_currentuserinfo() {
	global $user_login, $userdata, $user_level, $user_ID, $user_nickname, $user_email, $user_blog, $user_pass_md5, $user_identity;
	// *** retrieving user's data from cookies and db - no spoofing

	if (isset($_COOKIE['tripreaderuser_' . COOKIEHASH])) {
		$user_login = $_COOKIE['tripreaderuser_' . COOKIEHASH];
		$userdata = get_userdatabylogin($user_login);
		$user_level = $userdata->user_level;
		$user_ID = $userdata->ID;
		$user_nickname = $userdata->user_nickname;
		$user_email = $userdata->user_email;
		$user_blog = $userdata->user_blog;
		$user_pass_md5 = md5($userdata->user_pass);
		return true;
	}
	else
		return false;
}
endif;

if ( !function_exists('get_userdata') ) :
function get_userdata($userid) {
	global $trdb;
	$userid = (int) $userid;
	if ( empty($cache_userdata[$userid]) && $userid != 0) {
		$cache_userdata[$userid] = $trdb->get_row("SELECT * FROM $trdb->users WHERE ID = $userid");
		$cache_userdata[$cache_userdata[$userid]->user_login] =& $cache_userdata[$userid];
	} 
	if(isset($cache_userdata[$userid]))
		return $cache_userdata[$userid];
	else
		return "";
}
endif;

if ( !function_exists('get_userdatabylogin') ) :
function get_userdatabylogin($user_login) {
	global $cache_userdata, $trdb;
	if ( !empty($user_login) && empty($cache_userdata[$user_login]) ) {
		$user = $trdb->get_row("SELECT * FROM $trdb->users WHERE user_login = '$user_login'"); /* todo: get rid of this intermediate var */
		$cache_userdata[$user->ID] = $user;
		$cache_userdata[$user_login] =& $cache_userdata[$user->ID];
	} else {
		$user = $cache_userdata[$user_login];
	}
	return $user;
}
endif;

if ( !function_exists('auth_redirect') ) :
function auth_redirect() {
	// Checks if a user is logged in, if not redirects them to the login page
	if ( (!empty($_COOKIE['tripreaderuser_' . COOKIEHASH]) && 
				!tr_login($_COOKIE['tripreaderuser_' . COOKIEHASH], $_COOKIE['tripreaderpass_' . COOKIEHASH], true)) ||
			 (empty($_COOKIE['tripreaderuser_' . COOKIEHASH])) ) {
		header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-cache, must-revalidate, max-age=0');
		header('Pragma: no-cache');
	
		header('Location: ' . get_settings('siteurl') . '/?login&redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
		exit();
	}
}
endif;

if ( !function_exists('is_auth') ) :
function need_auth() {
	// Checks if a user is logged in, if not redirects them to the login page
	if ( (!empty($_COOKIE['tripreaderuser_' . COOKIEHASH]) && 
				!tr_login($_COOKIE['tripreaderuser_' . COOKIEHASH], $_COOKIE['tripreaderpass_' . COOKIEHASH], true)) ||
			 (empty($_COOKIE['tripreaderuser_' . COOKIEHASH])) ) {
		return true;
	}
	else
		return false;
}
endif;

if ( !function_exists('tr_redirect') ) :
function tr_redirect($location) {
	header("Location: $location");
}
endif;

function tr_logout() {
	tr_clearcookie();
}

if ( !function_exists('tr_login') ) :
function tr_login($username, $password, $already_md5 = false) {
	global $trdb, $error;

	if ( !$username )
		return false;

	if ( !$password ) {
		$error = '密码不能为空';
		return false;
	}

	$login = $trdb->get_row("SELECT ID, user_login, user_pass FROM $trdb->users WHERE user_login = '$username'");

	if (!$login) {
		$error = '用户名不存在';
		return false;
	} else {
		// If the password is already_md5, it has been double hashed.
		// Otherwise, it is plain text.
		if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
			return true;
		} else {
			$error = '密码错误.';
			$pwd = '';
			return false;
		}
	}
}
endif;

/***** Cookie functions *****/
if ( !function_exists('tr_setcookie') ) :
function tr_setcookie($username, $password, $already_md5 = false, $home = '', $siteurl = '') {
	if ( !$already_md5 )
		$password = md5( md5($password) ); // Double hash the password in the cookie.

	if ( empty($home) )
		$cookiepath = COOKIEPATH;
	else
		$cookiepath = preg_replace('|https?://[^/]+|i', '', $home . '/' );

	if ( empty($siteurl) ) {
		$sitecookiepath = SITECOOKIEPATH;
		$cookiehash = COOKIEHASH;
	} else {
		$sitecookiepath = preg_replace('|https?://[^/]+|i', '', $siteurl . '/' );
		$cookiehash = md5($siteurl);
	}

	setcookie('tripreaderuser_'. $cookiehash, $username, time() + 31536000, $cookiepath);
	setcookie('tripreaderpass_'. $cookiehash, $password, time() + 31536000, $cookiepath);

	if ( $cookiepath != $sitecookiepath ) {
		setcookie('tripreaderuser_'. $cookiehash, $username, time() + 31536000, $sitecookiepath);
		setcookie('tripreaderpass_'. $cookiehash, $password, time() + 31536000, $sitecookiepath);
	}
}
endif;

if ( !function_exists('tr_clearcookie') ) :
function tr_clearcookie() {
	setcookie('tripreaderuser_' . COOKIEHASH, ' ', time() - 31536000, COOKIEPATH);
	setcookie('tripreaderpass_' . COOKIEHASH, ' ', time() - 31536000, COOKIEPATH);
	setcookie('tripreaderuser_' . COOKIEHASH, ' ', time() - 31536000, SITECOOKIEPATH);
	setcookie('tripreaderpass_' . COOKIEHASH, ' ', time() - 31536000, SITECOOKIEPATH);
}
endif;

/***** User Register functions *****/
function is_username_too_short($user) {
	if (strlen(trim($user)) < 4) :
		return true;
	endif;
	
	return false;
}
	
function is_username_exist($user) {
	global $trdb;

	$number = $trdb->get_var("SELECT count(user_login) FROM $trdb->users WHERE user_login = '$user'");

	if ($number != 0) :
		return true;
	endif;

	return false;
}

/***** User Top Links *****/
/* 有图片的top bar
function get_user_top($is_echo=true) {
	global $user_login;

	if( (!empty($_COOKIE['tripreaderuser_' . COOKIEHASH]) && 
				!tr_login($_COOKIE['tripreaderuser_' . COOKIEHASH], $_COOKIE['tripreaderpass_' . COOKIEHASH], true)) ||
			 (empty($_COOKIE['tripreaderuser_' . COOKIEHASH])) ) {
		$user_top = "<SPAN><A href=\"./?register&redirect_to=".urlencode($_SERVER['REQUEST_URI'])."\"><img align=\"absmiddle\" border=\"0\" src=\"".bloginfo('stylesheet_directory',false)."/img/register.gif\">&nbsp;注册</A></SPAN><SPAN><A href=\"./?login&redirect_to=".urlencode($_SERVER['REQUEST_URI'])."\"><img align=\"absmiddle\" border=\"0\" src=\"".bloginfo('stylesheet_directory',false)."/img/login.gif\">&nbsp;登录</A></SPAN>";
	}
	else {
		//$user_login = $_COOKIE['tripreaderuser_' . COOKIEHASH];
		get_currentuserinfo();
		$user_top = "<SPAN onmousemove='moveBubble(event);' onmouseover='showBubble(event, \"\", \"查看您收藏的文章和创建的旅行计划。\");' onmouseout='hideBubble();'><A href=\"./?user=$user_login\"><img align=\"absmiddle\" border=\"0\" src=\"".bloginfo('stylesheet_directory',false)."/img/user.gif\">&nbsp;".$user_login."的个人资料</A></SPAN><SPAN onclick=\"javascript:xajax_logoutFunc();\"><A href=\"javascript://\"><img align=\"absmiddle\" border=\"0\" src=\"".bloginfo('stylesheet_directory',false)."/img/logout.gif\">&nbsp;退出</A></SPAN>";
	}
	if($is_echo)
		echo $user_top;
	else
		return $user_top;
}
*/

function get_user_top($is_echo=true) {
	global $user_login;

	if( (!empty($_COOKIE['tripreaderuser_' . COOKIEHASH]) && 
				!tr_login($_COOKIE['tripreaderuser_' . COOKIEHASH], $_COOKIE['tripreaderpass_' . COOKIEHASH], true)) ||
			 (empty($_COOKIE['tripreaderuser_' . COOKIEHASH])) ) {
		$user_top = "<SPAN><A href=\"./?register&redirect_to=".urlencode($_SERVER['REQUEST_URI'])."\">&nbsp;注册</A></SPAN><SPAN><A href=\"./?login&redirect_to=".urlencode($_SERVER['REQUEST_URI'])."\">&nbsp;登录</A></SPAN>";
	}
	else {
		//$user_login = $_COOKIE['tripreaderuser_' . COOKIEHASH];
		get_currentuserinfo();
		$user_top = "<SPAN onmousemove='moveBubble(event);' onmouseover='showBubble(event, \"\", \"查看您收藏的文章。\");' onmouseout='hideBubble();'><A href=\"./?user=$user_login&profile\">&nbsp;".$user_login."的个人资料</A></SPAN><SPAN onclick=\"javascript:xajax_logoutFunc();\"><A href=\"javascript://\">&nbsp;退出</A></SPAN>";
	}
	if($is_echo)
		echo $user_top;
	else
		return $user_top;
}

function check_userlogin() {

	if( !empty($_COOKIE['tripreaderuser_' . COOKIEHASH]) && 
				tr_login($_COOKIE['tripreaderuser_' . COOKIEHASH], $_COOKIE['tripreaderpass_' . COOKIEHASH], true)) {
		header("Location: ".get_settings('siteurl'));
	}
}

/***** 用户权限管理 ******/

/* returns true if $user_id can edit $post_id */
function user_can_edit_post() {
	
	global $user_ID, $user_level;
	$post_author_id = the_post_author_id(false);
	
	get_currentuserinfo();

	if ( ($user_ID == $post_author_id)
	     || ($user_level >= 10) ) {
		return true;
	} else {
		return false;
	}
}

function user_can_edit_plan() {
	
	global $user_ID, $user_level;
	$post_author_id = the_post_user_id(false);
	
	get_currentuserinfo();

	if ( ($user_ID == $post_author_id)
	     || ($user_level >= 10) ) {
		return true;
	} else {
		return false;
	}
}

function check_user_can_editpost($post_id){
	global $user_ID, $user_level, $trdb;
	$request = "SELECT post_author FROM $trdb->posts WHERE ID = $post_id";
	$author_id = $trdb->get_var($request);

	get_currentuserinfo();

	if ( ($user_ID == $author_id)
	     || ($user_level >= 10) ) {
		return;
	} else {
		header("Location: ".get_option('siteurl'));
	}
}

function check_user_is_admin(){
	global $user_level;

	get_currentuserinfo();

	if ( $user_level >= 10 ) {
		return;
	} else {
		header("Location: ".get_option('siteurl'));
	}
}

function check_user_can_see_draft(){
	global $user_level;

	get_currentuserinfo();

	if ( $user_level >= 10 ) {
		return true;
	} else {
		return false;
	}
}

function user_can_hide_post() {
	
	global $user_ID, $user_level;
	
	get_currentuserinfo();

	if ($user_level >= 10) {
		return true;
	} else {
		return false;
	}
}

function user_can_edit_profile() {

	$profile_user = the_user_id(false);
	$current_user = get_currentuserid(false);

	if($profile_user != $current_user)
		return false;
	else
		return true;
}

function user_can_unfavor_post() {
	//global $trdb;

	//$current_user = get_currentuserid(false);
	//$current_post_id = the_post_id(false);

	//$request = "SELECT count(rel_id) FROM $trdb->post2user WHERE post_id=$current_post_id AND user_id=$current_user";
	//$number = $trdb->get_var($request);

	//if(user_can_edit_profile()&&($number!=0)&&is_user_home())
	if(user_can_edit_profile()&&is_user_home())
		return true;
	else
		return false;
}

function user_can_readfullpost() {
	
	global $user_ID, $user_level;
	
	get_currentuserinfo();

	if ($user_level >= 0) {
		return true;
	} else {
		return false;
	}
}

?>